//
//  ReturnedDepositController.swift
//  ShareCar
//
//  Created by jiuzhongkeji on 2019/1/8.
//  Copyright © 2019 changqingkeji. All rights reserved.
//

import UIKit

class ReturnedDepositController: UIViewController {
    
    var returnMoneyNumber: String!
    var bankID : String!
    var type: Int!

    @IBOutlet weak var openBankTextFeld: UITextField!
    @IBOutlet weak var cardNumberTextField: UITextField!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var bankNameLabel: UILabel!
    @IBOutlet weak var returnCountLabel: UILabel!
    @IBOutlet weak var messageLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        returnCountLabel.text = returnMoneyNumber+"元"
        nameLabel.text = User.info()?.username
        messageLabel.text = slipViewController?.config?.depositOverInstruction
    }
    //MARK: --IBAction
    @IBAction func chooseBank(_ sender: UITapGestureRecognizer) {
        performSegue(withIdentifier: "chooseBankSence", sender: nil)
    }
    
    @IBAction func commit(_ sender: UIButton) {
        
        guard cardNumberTextField.text != "" else {
            showError("卡号不能为空，请重新输入（2214)")
            return
        }
        
        let teleiphone = cardNumberTextField.text!.removeAllSpace()
        guard (15...19).contains(teleiphone.count) else {
            showError("卡号长度不正确，请重新输入（2215）")
            return
        }

        guard bankID != nil else {
            showError("银行不能为空，请选择银行(2216)")
            return
        }
        
        guard openBankTextFeld.text != "" else {
            showError("开户行不能为空，请填写开户行信息(2217)")
            return
        }
        guard  let value = openBankTextFeld.text, value.count <= 20 else {
            showError("开户行长度超限，请重新输入(2218)")
            return
        }
        
        let number = cardNumberTextField.text?.removeAllSpace()
        JZLoading.showLoadingWith(toView: view)
        User.saveCardInfo(type: type, cardNumber: number!, bankId: bankID, openBank: openBankTextFeld.text!, success: {  [weak self] in
            JZLoading.hideLoading()
            self?.showError("退款申请已提交，退款预计7个工作日到账，请耐心等待")
            self?.navigationController?.popViewController(animated: true)
        }) { [weak self] error in
            JZLoading.hideLoading()
            self?.showError(error.msg)
        }
    
        
    }
        
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if  segue.identifier == "chooseBankSence" {
            if let vc = segue.destination as? BankListViewController {
                vc.block = { [weak self] bank in
                    self?.bankNameLabel.text = bank.bankName
                    self?.bankNameLabel.textColor = UIColor(hexString: "#0a0b41")
                    self?.bankID = bank.bankId
                }
            }
        }
    }
}


extension ReturnedDepositController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        var text = textField.text! as NSString
        //设置格式为数字
        let characterSet = NSCharacterSet(charactersIn: "0123456789")
        //去掉空格
        let str = string.replacingOccurrences(of: " ", with: "")
        let nsStr = str as NSString
        if nsStr.rangeOfCharacter(from: characterSet.inverted).location != NSNotFound {
            return false
        }
        //将输入的数字添加给textfield
        text = text.replacingCharacters(in: range, with: string) as NSString
        //去掉空格
        text = text.replacingOccurrences(of: " ", with: "") as NSString
        
        var newString = ""
        while text.length > 0 {
            let substring = text.substring(to: getMin(num1: text.length, num2: 4))
            newString = newString.appendingFormat(substring)
            if substring.count == 4 {
                newString = newString.appendingFormat(" ")
            }
            text = text.substring(from: getMin(num1: text.length, num2: 4)) as NSString
        }
        
        newString = newString.trimmingCharacters(in: characterSet.inverted)
        if newString.count >= 24 { //设置银行卡位数为16
            return false
        }
        textField.text = newString
        if string.bytes.first == nil {
            var loc = range.location
            if loc > newString.count {
                loc = newString.count
            }
            let r = NSRange(location: loc, length: 0)
            textField.setSelectedRange(r)
        } else if nsStr.rangeOfCharacter(from: characterSet.inverted).location == NSNotFound {
            var loc = range.location + 1
            if loc % 5 == 0 {
                loc += 1
            }
            let r = NSRange(location: loc, length: 0)
            textField.setSelectedRange(r)
        }
        return false
        
    }
    
    func getMin(num1 : Int, num2: Int) -> Int {
        if num1 <= num2 {
            return num1
        } else {
            return num2
        }
    }
}
